<template>

  <div class="layout">
    <el-tabs type="border-card">
      <el-tab-pane label="登录" v-if="this.$route.meta.flag">
        <el-form
            label-position="right"
            label-width="80px"
            style="max-width: 460px"
            class="loginForm"
            :model="form"
            ref="loginFormRef"
        >
          <el-form-item
              label="邮箱："
              prop="uid"
              :rules="[{ required: true, message: '请输入邮箱', trigger: 'blur' }]"

          >
            <el-input v-model="form.uid"/>
          </el-form-item>
          <el-form-item
              :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
              prop="password" label="密码：">
            <el-input type="password" v-model="form.password" />
          </el-form-item>

          <el-row>
            <el-checkbox
                class="checkBox"
                v-model="form.isAgree"
                label="同意用户使用准则"
                name="type"
            />
          </el-row>
          <el-button
              v-if="form.isAgree"
              type="primary"
              class="loginBtn"
              @click="login"
          >
            登录
          </el-button>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="注册" v-else>
        <el-form
            label-position="right"
            label-width="100px"
            style="max-width: 460px"
            class="loginForm"
            :model="registerForm"
            ref="registerFormRef"
        >
          <el-form-item label="邮箱："
                        prop="uid"
                        :rules="[{ required: true, message: '请输入邮箱', trigger: 'blur' }]"
          >
            <el-input v-model="registerForm.uid" />
          </el-form-item>
          <el-form-item label="密码："
                        prop="password"
                        :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
          >
            <el-input type="password" v-model="registerForm.password" />
          </el-form-item>
          <el-form-item label="确认密码："
                        prop="confirmPassword"
                        :rules="[{ required: true, message: '请输入确认密码', trigger: 'blur' }]"
          >
            <el-input
                type="password"
                v-model="registerForm.confirmPassword"
                @blur="confirmFunc"
            />
          </el-form-item>
          <el-form-item label="验证码："
                        prop="identifyCode"
                        :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]"
          >
            <el-row>
              <el-input
                  type="password"
                  v-model="registerForm.identifyCode"
                  class="inpWidth"
              />
              <el-button type="primary" @click="getIdentifyCode" plain>
                获取验证码
              </el-button>
            </el-row>
          </el-form-item>

          <el-row>
            <el-checkbox
                class="checkBox"
                v-model="registerForm.rAgree"
                label="同意用户使用准则"
                name="type"
            />
          </el-row>
          <el-button
              v-if="registerForm.rAgree"
              type="primary"
              class="loginBtn"
              @click="register"
          >
            注册
          </el-button>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>

</template>

<script>

import { reactive, toRefs,ref } from "@vue/reactivity";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router"
import api from "../api/api.js";
import { useStore } from 'vuex';

export default {
  name: 'Login',
  components: {
    ElMessage,
    reactive,
    toRefs
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const form = reactive({
      uid: "",
      password: "",
      isAgree: 0,
    });
    const registerForm = reactive({
      uid: "",
      password: "",
      confirmPassword: "",
      identifyCode: "",
      rAgree: 0,
    });
    const loginFormRef = ref();
    const registerFormRef = ref();
    // 方法
    // 登录
    function login() {
      loginFormRef.value.validate(valid => {
        if(!valid) return;
        console.log(form);
        api
            .Login(form)
            .then((res) =>{
              if (res.data[0].uid == form.uid && res.data[0].password == form.password)
              {
                ElMessage.success('登录成功')
                localStorage.clear(); // 登录成功前先清空，防止用户自己设置localStorage
                localStorage.setItem('uid', res.data[0].uid);
                localStorage.setItem('password', res.data[0].password);
                store.commit("modifyFalse"); // 直接点登录重新登录的时候要先退出
                if (res.data[0].sudo == '1') {
                    localStorage.setItem('sudo', res.data[0].sudo)
                    ElMessage.success('管理员登录')
                    store.commit("modifyTrue");
                }
                if (route.query.redirect == null) router.push("/");
                else router.push(route.query.redirect);
              }
              else {
                ElMessage.error('登录失败')
              }
            })

      })
    };
    // 注册
    const register = () => {
      registerFormRef.value.validate(valid => {
        if(!valid) return;
        console.log("注册", registerForm);
        api
            .Register(registerForm)
            .then((res) => {
              // 若已经注册过则无效
              if (res && res.data.result == '注册成功')
              {
                ElMessage.success('注册成功');
              }
              else if(res && res.data.result == '该账号已注册')
              {
                ElMessage.error('该账号已注册');
              }
            })
      })
      router.replace("/");
    };
    // 获取验证码
    function getIdentifyCode() {
      console.log("获取验证码");
      api
          .GetVerityCode({'uid':registerForm.uid})
          .then((res) => {
            if (res && res.data.result == '该账号已注册')
            {
              ElMessage.error('该账已注册');
            }
            else
            {
              ElMessage.success('请去邮箱查看验证码')
            }
          })
    };
    // 确认密码
    // function confirmFunc() {
    //   if (registerForm.confirmPassword !== registerForm.rPassword)
    //     alert("密码与确认密码不一致");
    // }
    const confirmFunc = () => {
      if (registerForm.confirmPassword !== registerForm.password)
        ElMessage.error("密码与确认密码不一致.");
    };
    return {
      form,
      registerForm,
      login,
      register,
      getIdentifyCode,
      confirmFunc,
      registerFormRef,
      loginFormRef,
    };
  }
};

</script>

<style scoped>

.layout {
  position: absolute;
  left: calc(50% - 200px);
  top: 20%;
  width: 400px;
}
.loginBtn {
  width: 100px;
}
.loginForm {
  text-align: center;
}
.checkBox {
  margin-left: 7px;
}
.inpWidth {
  width: 165px;
}

</style>
